<?php
namespace app\index\controller;

use app\common\model\DocArticleModel;
use app\common\model\DocModel;

class Doc extends Common
{
    /**
     * 查看文档
     * @author 贺强
     * @time   2023/4/21 16:42
     */
    public function info()
    {
        $id = $this->request->param('id', '');
        $doc = DocModel::getModel(['id' => $id], ['name', 'is_open', 'password']);
        if (empty($doc)) {
            return '文档不存在';
        }
        if ($doc['is_open'] === 0) {
            if ($this->request->isPost()) {
                $pwd = $this->request->post('pwd', '');
                $pwd = get_md5_password($pwd);
                if ($pwd !== $doc['password']) {
                    return ajax('密码错误', 401);
                }
                cookie('_doc_pwd', $pwd, 7200);
                return ajax('验证成功');
            }
            if (empty(cookie('_doc_pwd')) || cookie('_doc_pwd') !== $doc['password']) {
                return view('login', ['id' => $id]);
            }
        }
        $article = DocArticleModel::getList(['doc_id' => $id], ['content'], null, ['sort']);
        $chapter = count($article);
        $section = 0;
        foreach ($article as $item) {
            $section += substr_count($item['content'], '###');
        }
        return view('', compact('doc', 'article', 'chapter', 'section'));
    }
}
